﻿using Ids4.Api.Data.Mysql.Repository;
using Ids4.Api.Models.Consts;
using Ids4.Api.Services;
using Ids4.Api.Services.Impl;
using System.Reflection;

namespace Ids4.Api.Application.Infrastructure
{
    internal class AutofacModule : Autofac.Module
    {
        private ConfigurationManager _configurationManager;
        internal AutofacModule(ConfigurationManager configurationManager)
        {
            _configurationManager = configurationManager;
        }

        protected override void Load(ContainerBuilder builder)
        {
            var assembly = Assembly.GetExecutingAssembly();

            var databaseType = _configurationManager.GetSection("DataBase")["Type"];
            if (databaseType.ToLower() == DatabaseConst.Mysql)
            {
                builder.RegisterGeneric(typeof(MysqlApplicationRepository<>)).As(typeof(IApplicationRepository<>)).InstancePerLifetimeScope();
                builder.RegisterGeneric(typeof(MysqlConfigurationRepository<>)).As(typeof(IConfigurationRepository<>)).InstancePerLifetimeScope();
                builder.RegisterType(typeof(MysqlApiScopeRepository)).As(typeof(IScopeRepository)).InstancePerLifetimeScope();
            }
            else
            {
                //builder.RegisterGeneric(typeof(SqlServerApplicationRepository<>)).As(typeof(IApplicationRepository<>)).InstancePerLifetimeScope();
                //builder.RegisterGeneric(typeof(ConfigurationRepository<>)).As(typeof(IConfigurationRepository<>)).InstancePerLifetimeScope();
                //builder.RegisterType(typeof(ApiScopeRepository)).As(typeof(IScopeRepository)).InstancePerLifetimeScope();
            }

            builder.RegisterGeneric(typeof(ApplicationBaseService<>)).As(typeof(IApplicationBaseService<>));
            //builder.RegisterType<AuthCodeService>().As<IAuthCodeService>();

            builder.RegisterAssemblyTypes(assembly)
              .Where(t => t.Name.EndsWith("Service"))
              .AsImplementedInterfaces()
              .InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(assembly)
             .Where(t => t.Name.EndsWith("Repository"))
             .InstancePerLifetimeScope()
             .PreserveExistingDefaults();
        }
    }
}
